package org.idea.spring.dependency.inject.type;

import org.idea.spring.ioc.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * @Author linhao
 * @Date created in 4:02 下午 2021/4/23
 */
public class QualifierInjectDemo {

    @Autowired
//    @Resource
    //按照user2的名字进行字段注入，这里会注入user2的对象实例
    //如果加入了@Resource注解的话，就会注入user1对象，而且优先级比user2要高
    @Qualifier("user2")
    private User user1;

//    @Autowired
    @Resource
    private User user2;

    @Autowired
    @Qualifier //这里带有@Qualifier注解之后，会自动注入person() 这个bean
    private Person person;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(QualifierInjectDemo.class);
        applicationContext.refresh();
        QualifierInjectDemo beanDemo = applicationContext.getBean(QualifierInjectDemo.class);
        System.out.println("user1：" + beanDemo.user1);
        System.out.println("user2：" + beanDemo.user2) ;
        System.out.println("普通：" + beanDemo.user1);
        System.out.println("person 分组："+beanDemo.person);
        applicationContext.close();
    }

    @Bean
    @Qualifier
    public Person person(){
        return new Person(1,"idea");
    }

    @Bean
    public Person femalePerson(){
        return new Person(2,"idea2");
    }

    @Bean
    public User user1(){
        return createUser("user1");
    }

    @Bean
    public User user2(){
        return createUser("user2");
    }


    private static User createUser(String name) {
        User user = new User();
        user.setName(name);
        return user;
    }
}
